<template>
  <div class="file-manager">
    <el-container>
      <el-header class="file-manager-header">
        <h2>文件列表</h2>
        <el-button type="primary" @click="handleUploadClick">上传文件</el-button>
      </el-header>
      <el-main class="file-manager-main">
        <!-- 文件列表将在这里展示 -->
        <!-- <p>文件列表加载中...</p> --> <!-- 移除占位符 -->
        <!-- 启用 Element Plus 表格 -->
        <el-table :data="fileList" style="width: 100%" v-loading="loading">
          <el-table-column prop="originalFileName" label="文件名" sortable></el-table-column>
          <el-table-column prop="fileSize" label="大小" sortable :formatter="formatFileSize"></el-table-column>
          <el-table-column prop="uploadTime" label="上传日期" sortable></el-table-column>
          <el-table-column label="操作" width="240">
            <template #default="scope">
              <el-button size="small" @click="handlePreview(scope.row)">预览</el-button>
              <el-button size="small" @click="handleDownload(scope.row)">下载</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>

    <!-- 文件上传对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="上传文件" @close="handleUploadDialogClose">
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        action="http://101.34.246.109:9877/upload"
        :auto-upload="false"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :on-exceed="handleUploadExceed"
        :limit="5"
        multiple
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <el-button class="ml-3" type="success" @click="submitUpload" style="margin-left: 10px;">
          上传到服务器
        </el-button>
        <template #tip>
          <div class="el-upload__tip">
            可选择多个文件，单个文件不超过 500MB (示例限制)
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">关闭</el-button>
          
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts"> // 添加 lang="ts"
import { ref, onMounted } from 'vue';
import { ElContainer, ElHeader, ElMain, ElButton, ElTable, ElTableColumn, ElDialog, ElUpload, ElMessage } from 'element-plus';
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'

// --- 状态引用 ---
const uploadRef = ref<UploadInstance>()
const fileList = ref<FileInfo[]>([]); // 使用接口定义文件列表类型
const uploadDialogVisible = ref(false);
const loading = ref(false); // 控制表格加载状态

// --- 接口定义 ---
interface FileInfo {
  id: number; // 文件唯一标识
  fileName: string;
  originalFileName: string;
  filePath: string;
  fileSize: number;
  fileType: string;
  uploadTime: string; // 上传日期
}

// --- 数据获取与处理 ---

// 获取文件列表的函数
const fetchFileList = async () => {
  console.log('Fetching file list...');
  loading.value = true;
  try {
    // 调用后端 API 获取文件列表
    const response = await fetch('http://101.34.246.109:9877/api/files');
    const data = await response.json();
    console.log('File list from API:', data); // 打印返回结果
    fileList.value = data.files;

    // await new Promise(resolve => setTimeout(resolve, 500)); // 模拟网络延迟
    // fileList.value = [
    //   { id: 1, name: '用户手册.pdf', size: 1258291, uploadDate: '2024-03-15', url: '/uploads/manual.pdf' },
    //   { id: 2, name: '项目Logo.png', size: 51200, uploadDate: '2024-03-14', url: '/uploads/logo.png' },
    //   { id: 3, name: '会议记录.docx', size: 24576, uploadDate: '2024-03-13', url: '/uploads/meeting.docx' },
    //   { id: 'abc', name: '测试图片.jpg', size: 1024 * 1024 * 2.5, uploadDate: '2024-03-12', url: '/uploads/test.jpg' },
    // ];

  } catch (error) {
    console.error('Failed to fetch file list:', error);
    ElMessage.error('获取文件列表失败');
  } finally {
    loading.value = false;
  }
};

// 格式化文件大小
const formatFileSize = (row: FileInfo, column: any, cellValue: number, index: number): string => {
  if (cellValue === null || cellValue === undefined) return '未知';
  
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  let size = cellValue;
  let unitIndex = 0;
  
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }
  
  // 保留两位小数
  return `${size.toFixed(2)} ${units[unitIndex]}`;
}

// 处理上传按钮点击事件
const handleUploadClick = () => {
  uploadDialogVisible.value = true;
};

// 处理预览 (需要实现)
const handlePreview = (file: FileInfo) => {
  console.log('Previewing file:', file);
  if (file.filePath) {
    window.open(file.filePath, '_blank');
  } else {
    ElMessage.warning('该文件没有提供预览链接');
  }
};

// 处理下载 (需要实现)
const handleDownload = (file: FileInfo) => {
  console.log('Downloading file:', file);
  window.location.href = `http://101.34.246.109:9877/download/${file.id}`;
};

// 处理删除 (需要实现)
const handleDelete = (file: FileInfo) => {
  console.log('Deleting file:', file);
  // 调用后端 API 删除文件
  fetch(`http://101.34.246.109:9877/delete/${file.id}`, {
    method: 'POST',
  })
  .then(response => {
    if (response.ok) {
      // 删除成功
      fileList.value = fileList.value.filter(item => item.id !== file.id);
      ElMessage.success(`${file.fileName} 删除成功!`);
    } else {
      // 删除失败
      ElMessage.error(`${file.fileName} 删除失败!`);
    }
  })
  .catch(error => {
    console.error('Error deleting file:', error);
    ElMessage.error(`${file.fileName} 删除出错: ${error.message || '未知错误'}`);
  });
};

// --- 上传相关逻辑 ---

// 提交上传到服务器
const submitUpload = () => {
  uploadRef.value!.submit()
}

// 定义上传相关类型
interface UploadFile {
  name: string;
  [key: string]: any;
}

// 上传成功处理
const handleUploadSuccess = (response: any, uploadFile: UploadFile, uploadFiles: UploadFile[]) => {
  console.log('Upload success:', response, uploadFile);
  ElMessage.success(`${uploadFile.name} 上传成功!`);
  // 清理已上传列表交给 close 事件处理，避免重复清理
  fetchFileList(); // 上传成功后刷新文件列表
};

// 上传失败处理
const handleUploadError = (error: any, uploadFile: UploadFile, uploadFiles: UploadFile[]) => {
  console.error('Upload error:', error);
  ElMessage.error(`${uploadFile.name} 上传失败: ${error.message || '未知错误'}`);
};

// 文件超出个数限制时的处理
const handleUploadExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
    `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
      files.length + uploadFiles.length
    } 个文件`
  )
}

// 关闭上传对话框时清空已选择文件列表
const handleUploadDialogClose = () => {
    uploadRef.value!.clearFiles()
}


// --- 生命周期钩子 ---
onMounted(() => {
  fetchFileList();
});
</script>

<style scoped>
.file-manager {
  height: calc(100vh - 4rem); /* 减去可能的页眉/页脚高度 */
}

.file-manager-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
  padding-bottom: 1rem;
  margin-bottom: 1rem;
}

.file-manager-main {
  padding: 0; /* 根据需要调整 */
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>